<?php

class CartController extends Controller
{
    public function actionAddToCart() {

        $id = $_POST['id'];
        if (isset($_POST['prod_count'.$id])){
            $prod_count = $_POST['prod_count'.$id];
            if (is_numeric($prod_count))
                $prod_count = $_POST['prod_count'.$id] + 0;
            if (!is_int($prod_count) || $prod_count == 0) {
                $prod_count = -1;
            }
        }
        else $prod_count = 0;

        $cart_array = array();
        $cart_array = CartFunctions::getCartArray();

        if (isset($cart_array[$id])){
            if ($prod_count > 0)
                $cart_array[$id] = $prod_count;
            elseif ($prod_count === 0)
            $cart_array[$id] = $cart_array[$id] + 1;
        }
        else $cart_array[$id] = 1;

        CartFunctions::setCartArray($cart_array);

        $this->redirect('/korzina');
    }

    public function actionRemoveFromCart(){
        $id = $_POST['id'];
        $cart_array = array();
        $cart_array = CartFunctions::getCartArray();
        unset($cart_array[$id]);
        CartFunctions::setCartArray($cart_array);

        $this->redirect('/korzina');
    }

    public function actionShowCart(){
        $cart_array = array();
        $products = array();
        $cart_array = CartFunctions::getCartArray();
        if (is_array($cart_array)){
			$products = Product::model()->findAllByAttributes(array(
				'id'=>array_keys($cart_array),
			), array(
				'order'=>'title'
			));
		}
        $this->render('cart', array(
            'products'=>$products,
            'cart'=>$cart_array
        ));
    }
}
